import logging
import time

import openai
import requests
from fastapi import HTTPException

def validate_conversation_history(conversation_history):
    user_role_count = 0
    assistant_role_count = 0
    for index, message in enumerate(conversation_history):
        if message["role"] == "user":
            user_role_count += 1
        elif message["role"] == "assistant":
            assistant_role_count += 1
        if assistant_role_count > user_role_count:
            error_msg = f"对话历史中角色顺序错误，在第{index + 1}条消息（{message}）处出现了 role assistant 在 role user 之前的情况"
            logging.error(error_msg)
            raise ValueError(error_msg)
    return conversation_history

def qwen_intent_recognition(text: str, conversation_history, config):
    openai.api_base = config.QWEN_API_BASE
    openai.api_key = config.QWEN_API_KEY
    start_time = time.time()
    # 限制对话历史长度
    if len(conversation_history) > config.MAX_HISTORY_LENGTH:
        conversation_history = conversation_history[-config.MAX_HISTORY_LENGTH:]
    # 加入用户消息到对话历史
    conversation_history.append({"role": "user", "content": text})
    # 验证对话历史中的角色顺序
    conversation_history = validate_conversation_history(conversation_history)
    # 调用Qwen模型进行意图识别
    try:

        response = openai.ChatCompletion.create(
            model="Qwen",
            messages=conversation_history,
            stream=False,
            stop=[]
        )
        if not response.choices:
            raise HTTPException(status_code=400, detail="意图识别失败，模型未返回有效选择内容")
        result = response.choices[0].message.content
        conversation_history.append({"role": "assistant", "content": result})
        logging.info(f"Qwen对话历史: {conversation_history}")
        end_time = time.time()
        logging.info(f"Qwen回复耗时: {end_time - start_time}s")
        return conversation_history
    except requests.exceptions.RequestException as e:
        logging.error(f"网络连接出现问题导致意图识别失败: {e}")
        raise HTTPException(status_code=400, detail="意图识别失败，网络连接出现问题，请检查网络设置后重试。")
    except openai.error.AuthenticationError:
        logging.error("意图识别出现认证错误")
        raise HTTPException(status_code=400, detail="意图识别失败，认证信息有误，请检查 API 密钥等认证配置。")
    except Exception as e:
        logging.error(f"意图识别出现其他错误: {e}")
        raise HTTPException(status_code=500, detail="意图识别出现内部错误，请联系管理员。")